package com.fantasizegame.project;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class ImportStart {
	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {

		if (args.length < 1) {
			System.out.println("请输入可执行sql 文件");
			return;
		}
		File file = new File(args[0]);

		if (!file.exists()) {
			System.out.println("未找到可执行sql 文件");
			return;
		}
		if (!file.getName().endsWith(".sql")) {
			System.out.println("文件 【" + file.getName() + "】 不是 .sql 可执行sql 文件");
			return;
		}
		InputStream	is			= ImportStart.class.getClassLoader().getResourceAsStream("db.properties");

		Properties	properties	= new Properties();
		properties.load(is);

		String	url			= properties.getProperty("url");
		String	user		= properties.getProperty("user");
		String	password	= properties.getProperty("password");

		try (Connection conn = DriverManager.getConnection(url, user, password)) {
			Statement stmt = conn.createStatement();

			// 读取SQL文件并执行
			try (BufferedReader br = new BufferedReader(new FileReader(file))) {
				String			line;
				StringBuilder	sb	= new StringBuilder();
				while ((line = br.readLine().trim()) != null) {
					if (line.isEmpty()) {
						continue;
					}
					if (line.startsWith("--")) {
						continue;
					}
					sb.append(line);

					// 执行每一条SQL语句
					if (line.endsWith(";")) {
						System.out.println("sql : " + sb.toString() + " :sql");
						stmt.execute(sb.toString());
						sb = new StringBuilder();
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			// 进行数据库操作...
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
